<template>
	<view class="home">
		<view class="homenatop">
			<indexNav></indexNav>
			<view class="content">
				<view class="giar" v-for="v in list" :key="v.code" @click="$Router.push(v.pach)">
					<image class="home_block_list_img" :src="v.url" mode=""></image>
					<view class="home_block_list_text">{{ $t(v.name) }}</view>
				</view>
			</view>
		</view>
		<!-- 		<view class="">
			 <u-notice-bar :bgColor='' :text="notiContent" mode="link" speed="1000" ></u-notice-bar>
		</view> -->
		<view class="pl-20 pr-20">
			<view class="announcement">
				<view class="home_msg">
					<image class="w-30 h-30" src="@/static/imgs/gongao.png" mode=""></image>
					<view class="home_msg_con">
						<view class="h-60">
							<view class="msg_con">
								<view class="zuoce">
									{{ notifications[currentIndex] ? notifications[currentIndex].noticeContent : $t('home.h27') }}
								</view>
								<text class="zuoce_tiem">
									{{ notifications[currentIndex] ? notifications[currentIndex].createTime : '' }}
								</text>
								<image class="w-24 h-24 ml-10" src="@/static/imgs/jiantou.png" mode=""></image>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="zijin">
			<u-swiper keyName="imgUrl" :list="swiperList"></u-swiper>
			<!-- <image style="border-radius: 10px; width: 100%; height: 93px; float: left" src="@/static/imgs/zijinbac.png" mode=""></image> -->
		</view>
		<view class="" style="padding: 0px 10px; margin-top: 10px">
			<view class="home_block am-cf">
				<view class="home_block_list" v-for="(item, index) in Data" :key="item.code" @click="$Router.push(item.pach)">
					<view class="home_block_list_img mb-16">
						<image class="w-50 h-50" :src="item.url" mode=""></image>
					</view>
					<view style="font-size: 12px; color: rgb(51, 51, 51)">
						{{ $t(item.name) }}
					</view>
				</view>
			</view>
		</view>
		<view class="" style="padding: 10px 10px">
			<view class="centry">
				<view class="" style="width: 33.33%">
					<view class="centryrise" :class="centryshow ? 'rise' : 'centryrise'">
						<text>BTC</text>
					</view>
					<view class="centryrise2" :class="BTCList.diff > 0 ? 'rise' : 'centryrise2'">{{ BTCList.close }}</view>
					<view class="centryrise3" :class="BTCList.diff > 0 ? 'rise' : 'centryrise3'">
						<text class="mr-20">{{ BTCList.diff }}</text>
						<text>{{ BTCList.changePercent }}%</text>
					</view>
				</view>
				<view class="" style="width: 33.33%">
					<view class="centryrise" :class="centryshow ? 'rise' : 'centryrise'">
						<text>ETH</text>
					</view>
					<view class="centryrise2" :class="ETHList.diff > 0 ? 'rise' : 'centryrise2'">{{ ETHList.close }}</view>
					<view class="centryrise3" :class="ETHList.diff > 0 ? 'rise' : 'centryrise3'">
						<text class="mr-20">{{ ETHList.diff }}</text>
						<text>{{ ETHList.changePercent }}%</text>
					</view>
				</view>
				<view class="" style="width: 33.33%">
					<view class="centryrise" :class="centryshow ? 'rise' : 'centryrise'">
						<text>USDC</text>
					</view>
					<view class="centryrise2" :class="USDTList.diff > 0 ? 'rise' : 'centryrise2'">{{ USDTList.close }}</view>
					<view class="centryrise3" :class="USDTList.diff > 0 ? 'rise' : 'centryrise3'">
						<text class="mr-20">{{ USDTList.diff }}</text>
						<text>{{ USDTList.changePercent }}%</text>
					</view>
				</view>
			</view>
		</view>
		<view style="display: flex; padding: 0px 10px; margin-top: 0px">
			<view style="white-space: nowrap; width: 100%; overflow: scroll; border-bottom: 0px solid rgb(238, 238, 238)">
				<!-- <view class="danshu" > -->
				<view class="danshu" v-for="(item, index) in ciallist" :key="item.id" @click="$Router.push({ path: '/pages/category/detail', query: { id: item.id } })">
					<view class="danshu_top">
						<view class="line-clamp1">
							{{ item.title }}
						</view>
						<!-- <view class="cahnggui">常规</view> -->
					</view>
					<view class="danshu_botton">
						<view class="" style="text-align: center">
							<view class="" style="font-size: 24px; color: rgb(255, 37, 0); font-weight: bold; line-height: 25px">
								{{ item.avgRate }}

								<text style="font-size: 13px">%</text>
							</view>
							<view style="font-size: 12px; color: rgb(102, 102, 102); margin-top: 3px">{{ $t('home.h17') }}</view>
						</view>
						<view class="" style="text-align: center">
							<view class="" style="font-size: 22px; color: rgb(0, 0, 0); font-weight: bold; line-height: 25px">
								{{ item.days }}
								<text style="font-size: 13px">{{ $t('home.h28') }}</text>
							</view>
							<view
								style="
									font-size: 12px;
									color: rgb(102, 102, 102);
									margin-top: 3px;
									white-space: normal;
									word-wrap: break-word;
									word-break: break-word;
									overflow-wrap: break-word;
								"
							>
								{{ item.limitMin }} {{ item.coin }} {{ $t('home.h18') }}
							</view>
						</view>
						<view class="borton">{{ $t('home.h23') }}</view>
					</view>
				</view>
			</view>
		</view>
		<view style="display: flex; padding: 0px 10px; margin-top: 10px">
			<view class="" style="border-radius: 10px; background-color: rgb(255, 255, 255); padding: 10px 15px; width: 100%">
				<view class="display: flex; align-items: center; font-size: 14px; font-weight: bold;">
					{{ $t('home.h20') }}
					<image style="margin-left: 10px; width: 14px; height: 14px" src="@/static/imgs/you.png" mode=""></image>
				</view>
				<view style="color: rgb(136, 136, 136); font-size: 12px; margin-top: 5px">
					2025-04-10 22:37
					<text class="ml-20">{{ $t('home.h21') }}：{{ $t('home.h25') }}</text>
				</view>
				<view class="" style="display: flex; align-items: center">
					<view class="" style="flex: 1 1 0%">
						<view class="" style="display: flex; justify-content: center; margin: 10px 0px 5px">
							<view class="van-circle">
								<arprogress :activeColor="'rgb(20, 155, 121)'" :width="'140'" :inactiveColor="'rgb(227, 9, 49)'" :percent="percent">
									<text style="color: #777; font-size: 12px">USDT</text>
								</arprogress>
							</view>
						</view>
						<view class="" style="display: flex; align-items: center">
							<view class="" style="flex: 1 1 0%; text-align: center">
								<view class="" style="font-size: 13px; color: rgb(119, 119, 119)">{{ $t('home.h23') }}</view>
								<view class="" style="font-size: 15px; color: rgb(227, 9, 49); font-weight: bold">{{ percent }}%</view>
							</view>
							<view class="" style="flex: 1 1 0%; text-align: center">
								<view class="" style="font-size: 13px; color: rgb(119, 119, 119)">{{ $t('home.h24') }}</view>
								<view class="" style="font-size: 15px; color: rgb(20, 155, 121); font-weight: bold">{{ 100 - percent }}%</view>
							</view>
						</view>
					</view>
					<view class="" style="flex: 1 1 0%">
						<view class="" style="display: flex; justify-content: center; margin: 10px 0px 5px">
							<view class="van-circle">
								<arprogress :activeColor="'rgb(20, 155, 121)'" :width="'140'" :inactiveColor="'rgb(227, 9, 49)'" :percent="percent2">
									<text style="color: #777; font-size: 12px">USDT</text>
								</arprogress>
							</view>
						</view>
						<view class="" style="display: flex; align-items: center">
							<view class="" style="flex: 1 1 0%; text-align: center">
								<view class="" style="font-size: 13px; color: rgb(119, 119, 119)">{{ $t('home.h23') }}</view>
								<view class="" style="font-size: 15px; color: rgb(227, 9, 49); font-weight: bold">{{ percent2 }}%</view>
							</view>
							<view class="" style="flex: 1 1 0%; text-align: center">
								<view class="" style="font-size: 13px; color: rgb(119, 119, 119)">{{ $t('home.h24') }}</view>
								<view class="" style="font-size: 15px; color: rgb(20, 155, 121); font-weight: bold">{{ 100 - percent2 }}%</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view style="height: 200rpx"></view>
		<FooterNav :modelKey="1" />
	</view>
</template>

<script>
import arprogress from '@/components/ar-circle-progress/index.vue';
import indexNav from './components/indexNav.vue';
import FooterNav from '@/components/footer-nav/footer-nav.vue';
import pako from 'pako';

import { financiallist, getAllNoticeList,getUserInfo } from '@/api/index.js';
export default {
	components: {
		indexNav,
		arprogress,
		FooterNav
	},
	data() {
		return {
			percent: 45,
			percent2: 45,
			intervalId: null, // 定时器 ID，用于清理
			centryshow: true,
			notiContent: this.$t('index.i0'),
			list: [
				{
					url: require('@/static/imgs/home1.png'),
					name: 'home.h2',
					text: '我要充值',
					code: 'home1',
					pach: '/subPackages/userMenu/deposit'
				},
				{
					url: require('@/static/imgs/home2.png'),
					name: 'home.h3',
					text: '我要提现',
					code: 'home2',
					pach: '/subPackages/userMenu/withdraw'
				},
				{
					url: require('@/static/imgs/home3.png'),
					text: '基金',
					name: 'home.h4',
					code: 'home3',
					pach: '/pages/category/index'
				},
				{
					url: require('@/static/imgs/home4.png'),
					text: '公司资质',
					name: 'home.h26',
					code: 'home4',
					pach: '/pages/index/qualificationsDetail'
				},
				{
					url: require('@/static/imgs/home5.png'),
					text: '邀请好友',
					name: 'home.h5',
					code: 'home5',
					pach: '/subPackages/userGrid/team'
				}
			],
			Data: [
				// {
				//   url: require("@/static/imgs/home6.png"),
				//   text: "每日签到",
				//   code: "home6",
				// },
				{
					url: require('@/static/imgs/home7.png'),
					text: '会员等级',
					name: 'home.h8',
					code: 'home7',
					pach: '/pages/Grade/Grade'
				},
				{
					url: require('@/static/imgs/home8.png'),
					text: '实名认证',
					name: 'home.h9',
					code: 'home8',
					pach: '/subPackages/userGrid/business'
				},
				{
					url: require('@/static/imgs/home9.png'),
					text: '我的团队',
					name: 'home.h10',
					code: 'home9',
					pach: '/subPackages/userGrid/team'
				},
				{
					url: require('@/static/imgs/home10.png'),
					text: '安全保障',
					name: 'home.h11',
					code: 'home10',
					pach: '/subPackages/userOther/articleDetail'
				},
				{
					url: require('@/static/imgs/home11.png'),
					text: '客服服务',
					name: 'home.h12',
					code: 'home11',
					pach: '/pages/customerService/index'
				},
				// {
				//   url: require("@/static/imgs/home12.png"),
				//   text: "积分商城",
				//   code: "home12",
				// },
				// {
				//   url: require("@/static/imgs/home13.png"),
				//   text: "日利宝",
				//   code: "home13",
				// },
				{
					url: require('@/static/imgs/home14.png'),
					text: '财务明细',
					name: 'home.h13',
					code: 'home14',
					pach: '/subPackages/userGrid/moneyDetail'
				},
				{
					url: require('@/static/imgs/home15.png'),
					text: '我的投资',
					name: 'home.h14',
					code: 'home15',
					pach: '/subPackages/userGrid/myInvest'
				}
			],
			//
			socketUrl: 'wss://h5-api.mexcfinance.com/ws/00a5c5be-9d59-43c2-853b-ed13bf76ef80', // WebSocket地址
			reconnectAttempts: 0, // 重连次数
			maxReconnectAttempts: 5, // 最大重连次数
			reconnectInterval: null, // 重连定时器
			heartbeatInterval: null, // 心跳定时器
			USDTList: {
				close: 0,
				diff: 0,
				changePercent: 0
			},
			ETHList: {
				close: 0,
				diff: 0,
				changePercent: 0
			},
			BTCList: {
				close: 0,
				diff: 0,
				changePercent: 0
			},
			ciallist: [],
			swiperList: [],
			notifications: [], // 存储后端返回的通知数组
			currentIndex: 0 // 当前显示的通知索引
		};
	},
	onLoad() {},
	onShow() {
		this.inin();
	},
	onHide() {
		console.log('页面被隐藏');
		this.cleanUp(); // 清理资源
		// 清理定时器
		clearInterval(this.intervalId);
		this.isSocketOpen = false;
	},
	// 组件生命周期
	mounted() {
		this.initWebSocket(); // 初始化 WebSocket
		this.updatePercentage();
		// 每隔 1 秒更新一次
		this.intervalId = setInterval(this.updatePercentage, 3000);
	},
	methods: {
		// 更新随机数
		updatePercentage() {
			const randomChange = (Math.random() - 0.5) * 0.1; // 随机生成 -0.05 到 0.05 的小浮动
			const newBuy = Math.min(Math.max(this.percent + randomChange, 0), 100); // 保持在 0~100 范围内
			const newBuy2 = Math.min(Math.max(this.percent2 + randomChange, 0), 100); // 保持在 0~100 范围内

			this.percent = parseFloat(newBuy.toFixed(2));
			this.percent2 = parseFloat(newBuy2.toFixed(2));
		},
		async inin() {
			let resUserInfo = await getUserInfo();
			// 更新 userInfo 并存储到本地
			this.$store.commit('USE_RINFO', resUserInfo.data);
			let res = await financiallist({ isHot: 1 });
			this.ciallist = res.rows;
			let banner = await getAllNoticeList();
			if (res.code === 200) {
				this.swiperList = banner.data.ACTIVITY_NOTICE;
				this.notifications = banner.data.ROLL_NOTICE || []; // 将获取的通知数组存储
				this.startScrolling(); // 开始滚动
				this.notiContent = '';
			}
		},

		startScrolling() {
			// 定时滚动通知，每隔 3 秒切换一次
			setInterval(() => {
				if (this.notifications.length > 1) {
					this.currentIndex = (this.currentIndex + 1) % this.notifications.length;
				}
			}, 3000); // 3 秒切换一次
		},
		// 初始化 WebSocket
		initWebSocket() {
			uni.connectSocket({
				url: this.socketUrl,
				success: () => {
					console.log('WebSocket 连接成功');
					this.reconnectAttempts = 0; // 连接成功后重置重连次数
				},
				fail: (err) => {
					console.error('WebSocket 连接失败', err);
					this.handleReconnect(); // 处理断线重连
				}
			});
			// 确保订阅在连接成功后执行
			uni.onSocketOpen(() => {
				console.log('WebSocket 开启，开始订阅');
				this.startHeartbeat(); // 开始心跳机制
				this.subscribeToMarket(); // 订阅数据
			});
			// 收到消息
			uni.onSocketMessage((res) => {
				// console.log(res.data, 'res.data内容'); // 打印接收到的消息

				if (res.data instanceof ArrayBuffer) {
					try {
						// 将 ArrayBuffer 转为 Uint8Array
						const uint8Array = new Uint8Array(res.data);

						// 使用 pako 解压数据
						const text = pako.inflate(uint8Array, { to: 'string' });

						// 解析解压后的 JSON 数据
						const data = JSON.parse(text);
						// 如果是心跳 Ping 消息
						if (data.ping) {
							console.log('收到 Ping 消息:', data.ping);

							// 返回 Pong 消息
							uni.sendSocketMessage({
								data: JSON.stringify({ pong: data.ping })
							});
							console.log('已发送 Pong 响应:', data.ping);
						} else {
							console.log(data, '解压后的数据');
						}
					} catch (error) {
						console.error('解压或解析数据失败:', error);
					}
				} else {
					const data = JSON.parse(res.data);
					// console.log(data, '解压后的数据');
					if (data.symbol == 'usdc') {
						const diff = data.data.tick.close - data.data.tick.high;
						const changePercent = ((data.data.tick.close - data.data.tick.open) / data.data.tick.open) * 100;
						this.USDTList.close = data.data.tick.close.toFixed(3);
						this.USDTList.diff = diff.toFixed(3);
						this.USDTList.changePercent = changePercent.toFixed(3);
					}
					if (data.symbol == 'eth') {
						const diff = data.data.tick.close - data.data.tick.high;
						const changePercent = ((data.data.tick.close - data.data.tick.open) / data.data.tick.open) * 100;
						this.ETHList.close = data.data.tick.close.toFixed(3);
						this.ETHList.diff = diff.toFixed(3);
						this.ETHList.changePercent = changePercent.toFixed(3);
					}
					if (data.symbol == 'btc') {
						const diff = data.data.tick.close - data.data.tick.high;
						const changePercent = ((data.data.tick.close - data.data.tick.open) / data.data.tick.open) * 100;
						this.BTCList.close = data.data.tick.close.toFixed(3);
						this.BTCList.diff = diff.toFixed(3);
						this.BTCList.changePercent = changePercent.toFixed(3);
					}
					// console.error('res.data 不是 ArrayBuffer 类型');
				}
			});

			// 连接关闭
			// uni.onSocketClose(() => {
			//   console.warn("WebSocket 已关闭");
			//   this.handleReconnect(); // 处理断线重连
			// });

			// 连接错误
			// uni.onSocketError((err) => {
			//   console.error("WebSocket 出现错误:", err);
			//   this.handleReconnect(); // 处理断线重连
			// });
		},

		// 心跳机制
		startHeartbeat() {
			if (this.heartbeatInterval) clearInterval(this.heartbeatInterval);
			this.heartbeatInterval = setInterval(() => {
				const pingMsg = { ping: Date.now() };
				uni.sendSocketMessage({
					data: JSON.stringify(pingMsg),
					success: () => {
						console.log('发送心跳包:', pingMsg);
					},
					fail: (err) => {
						console.error('发送心跳包失败:', err);
					}
				});
			}, 30000); // 每30秒发送一次心跳包
		},

		// // 订阅市场数据
		subscribeToMarket() {
			// const msg = {
			// 	sub: 'market.btcusdt.kline.1min',
			// 	id: 'id1'
			// };
			const msg = { op: 'subscribe', type: 'DETAIL' };

			uni.sendSocketMessage({
				data: JSON.stringify(msg),
				success: () => {
					console.log('订阅成功:', msg);
				},
				fail: (err) => {
					console.error('订阅失败:', err);
				}
			});
		},

		// 处理断线重连
		handleReconnect() {
			if (this.reconnectAttempts >= this.maxReconnectAttempts) {
				console.error('达到最大重连次数，停止重连');
				return;
			}

			console.log(`尝试重新连接 (${this.reconnectAttempts + 1}/${this.maxReconnectAttempts})...`);
			this.reconnectAttempts += 1;

			// 设置重连间隔
			if (!this.reconnectInterval) {
				this.reconnectInterval = setInterval(() => {
					this.initWebSocket();

					if (this.reconnectAttempts >= this.maxReconnectAttempts) {
						clearInterval(this.reconnectInterval);
						console.error('重连失败，达到最大重连次数');
					}
				}, 2000); // 每 5 秒尝试重连一次
			}
		},

		// 清理资源
		cleanUp() {
			clearInterval(this.heartbeatInterval);
			clearInterval(this.reconnectInterval);
			this.heartbeatInterval = null;
			this.reconnectInterval = null;

			uni.closeSocket({
				success: () => {
					console.log('WebSocket 已关闭');
				},
				fail: (err) => {
					console.error('关闭 WebSocket 失败:', err);
				}
			});
		}
	},
	beforeDestroy() {
		this.cleanUp(); // 清理资源
		// 清理定时器
		clearInterval(this.intervalId);
	}
};
</script>

<style lang="scss" scoped>
.home {
	padding-top: 50px;
}
.homenatop {
	background: rgb(255, 105, 26);
}
.content {
	white-space: nowrap;
	width: 100%;
	height: 100px;
	overflow: hidden;
	display: flex;
	justify-content: space-between;
	padding: 0px 15px;
	background: rgb(255, 105, 26);
	.giar {
		max-width: 20%;
		margin-right: 0px;
		text-align: center;
		border-radius: 6px;
		margin-top: 10px;
		position: relative;
		color: rgb(51, 51, 51);
		.home_block_list_img {
			width: 30px;
			height: 30px;
			margin: 0 auto;
			display: block;
			margin-bottom: 8px;
		}
		.home_block_list_text {
			width: 100%;
			text-align: center;
			font-size: 13px;
			font-family: Microsoft YaHei;
			color: #fff;
			margin-top: 6px;
			white-space: normal; /* 允许换行 */
			word-wrap: break-word; /* 自动换行 */
			word-break: break-word; /* 新标准推荐 */
			overflow-wrap: break-word; /* 兼容性最好 */
		}
	}
}
.announcement {
	background: rgb(255, 255, 255);
	border-radius: 0px 0px 10px 10px;
	overflow: hidden;
	position: relative;
	.home_msg {
		height: 50px;
		border-top: 1px solid #eee;
		height: 60px;
		display: flex;
		align-items: center;
		margin: 0 10px;
	}
	.home_msg_con {
		margin-left: 5px;
		flex: 1;
		font-size: 14px;
		line-height: 21px;
		transition: transform 0.5s ease-in-out; /* 平滑过渡效果 */
		.msg_con {
			height: 30px;
			line-height: 30px;
			display: flex;
			align-items: center;
			.zuoce {
				overflow: hidden;
				text-overflow: ellipsis;
				display: -webkit-box;
				color: rgb(51, 51, 51);
				font-size: 13px;
				flex: 1 1 0%;
				max-width: 278px;
				white-space: nowrap;
			}
			.zuoce_tiem {
				font-size: 11px;
				color: rgb(102, 102, 102);
				margin-left: 5px;
			}
		}
	}
}
.zijin {
	border-radius: 10px;
	padding: 10px;
	overflow: hidden;
}
.home_block {
	background: rgb(255, 255, 255);
	border-radius: 10px;
	display: flex;
	align-items: center;
	// justify-content: space-between;
	flex-wrap: wrap;
	.home_block_list {
		width: 25%;
		margin-top: 15px;
		text-align: center;
	}
}
.am-cf {
	zoom: 1;
}
.am-fl {
	float: left;
}
.centry {
	border-radius: 10px 10px 0px 0px;
	overflow: hidden;
	padding: 15px 10px;
	background: rgb(255, 255, 255);
	display: flex;
	align-items: center;
	margin-top: 10px;
	justify-content: space-between;
}

.rise {
	color: rgb(227, 9, 49);
}
.fall {
	color: rgb(20, 155, 121);
}
.centryrise {
	display: flex;
	align-items: center;
	text-align: center;
	font-size: 13px;
	color: red;
	justify-content: center;
}
.centryrise2 {
	font-size: 18px;
	font-weight: bold;
	text-align: center;
	position: relative;
	top: 3px;
	color: rgb(20, 155, 121);
}
.centryrise3 {
	display: flex;
	justify-content: center;
	line-height: 23px;
	font-size: 12px;
	padding: 0px;
	border-radius: 4px;
	color: rgb(20, 155, 121);
}
.danshu {
	width: 90%;
	display: inline-block;
	margin-right: 10px;
	padding: 20px 15px 20px 15px;
	border-radius: 10px;
	position: relative;
	border: 0 solid #fff;
	background-size: 100% 100%;
	background-image: url('@/static/imgs/honback.png');
	.danshu_top {
		font-size: 14px;
		font-weight: 500;
		color: rgb(51, 51, 51);
		padding: 0px;
		margin-top: 5px;
		display: flex;
		align-items: center;
		.line-clamp1 {
			flex: 1 1 0%;
			-webkit-line-clamp: 1;
			overflow: hidden;
			text-overflow: ellipsis;
			display: -webkit-box;
			-webkit-box-orient: vertical;
		}
		.cahnggui {
			border: 1px solid rgb(255, 37, 0);
			color: rgb(255, 37, 0);
			padding: 1px 5px;
			border-radius: 3px;
			margin-left: 10px;
			font-size: 10px;
		}
	}
	.danshu_botton {
		border-radius: 6px;
		display: flex;
		align-items: center;
		height: 70px;
		padding-top: 10px;
		justify-content: space-between;
	}
	.borton {
		text-align: center;
		width: 75px;
		line-height: 25px;
		border-radius: 6px;
		background: rgb(255, 37, 0);
		color: rgb(255, 255, 255);
		font-size: 13px;
		font-weight: bold;
		margin-top: 0px;
	}
}
.danshu2 {
	background-image: url('@/static/imgs/honback2.png');
}
</style>
